package ru.aslanov.schedule.server.services;

import ru.aslanov.schedule.model.DataItem;
import ru.aslanov.schedule.model.Group;
import ru.aslanov.schedule.model.Level;
import ru.aslanov.schedule.model.Operation;
import ru.aslanov.schedule.server.AccessDeniedException;
import ru.aslanov.schedule.server.AccessManager;
import ru.aslanov.schedule.server.BackReference;
import ru.aslanov.schedule.server.gcalendar.GCalendarSyncService;

import javax.jdo.PersistenceManager;
import javax.jdo.annotations.PersistenceAware;
import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

/**
 * Created by IntelliJ IDEA.
 * Created: Feb 2, 2010 11:10:17 AM
 *
 * @author Sergey Aslanov
 */
@PersistenceAware
public class LevelService extends ScheduleChildService<Level> {
    private BackReference groupBackRef;

    public LevelService() {
        super("name");
        groupBackRef = new BackReference(Group.class, "levelKey");
        addBackRef(groupBackRef);
    }

    @Override
    protected Class<Level> getEntityClass() {
        return Level.class;
    }

    @Override
    protected void makeObjectPersistent(PersistenceManager pm, Level object, HttpServletRequest request) {
        getParent(pm, request).getLevels().add(object);
    }

    @Override
    protected void fillDataItem(DataItem dataItem, Level object, HttpServletRequest request, PersistenceManager pm) throws Exception {
        super.fillDataItem(dataItem, object, request, pm);
        setAttr(dataItem, "schedule", object.getSchedule());
        setAttr(dataItem, "id", object.getId());
        setAttr(dataItem, "name", object.getName());
        setAttr(dataItem, "url", object.getUrl());
    }

    @Override
    protected boolean checkPermission(Level existingEntity, HttpServletRequest request, PersistenceManager pm, Operation operation) throws AccessDeniedException {
        String scheduleKey = existingEntity != null ? existingEntity.getSchedule().getEncodedKey() : getParentKey(request);

        return AccessManager.getInstance().hasAccessToSchedule(scheduleKey,
                operation == Operation.VIEW ? Operation.VIEW : Operation.UPDATE);
    }

    @Override
    protected void onChange(PersistenceManager pm, Level object, Operation operation, final HttpServletRequest request) {
        if (operation == Operation.UPDATE) {
            final Collection groups = groupBackRef.getBackRefEntities(pm, object);
            final GCalendarSyncService syncService = new GCalendarSyncService();
            for (Object group : groups) {
                syncService.updateGroupSchedules(pm, (Group)group, null, false);
            }
            executeAfterCommit(new Runnable() {
                @Override
                public void run() {
                    syncService.sendEvents(getParentKey(request));
                }
            });

        }
    }
}
